/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name: 'step_filter',
			title: 'step过滤',
			type: 'LineEdit'
		},
		{
			name : 'rout',
			title : '外形层',
			type : 'LineEdit',
			property : {tool_tip : '外形层默认是gko'},
		},
		{
			name : 'ol_resize_value',
			title : '外形扩大值',
			type : 'LineEdit',
			property : {tool_tip : '外形扩大值,默认是2 um'},
		},
		{
			name : 'auto_save',
			title : '自动保存',
			type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'Yes'},
					{name:'no',text:'No'},
				],
				tool_tip:'是否自动保存料号开关'
			}
		},
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-23 Carver
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 删除外形线 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("================================>删除外形线");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step_filter:'net.+',
		step2:"net",
		max_via_size: "0.9mm",
		min_via_num: "100",
		equidistant_tolerance: "0.005mm", 
		auto_save: "No",
		rout: "ol",  //外形层
		ol_resize_value: 2,  //外形扩大值(单位 um)
		units: "mm",
		auto_save: "No",  //自动保存
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}

	var max_via_size = parseFloat(par.max_via_size);
	var equidistant_tolerance = parseFloat(par.equidistant_tolerance);
	var job = Job.toLowerCase()
	if(_.isEmpty(job)){throw "参数Job不存在"}
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }

	// 通过matrix获取board属性的层
	var matrix = GEN.getMatrix({job:job})
	var board_layer = Object.keys(matrix).reduce(function(a,b){
		if(matrix[b].context == "board" && matrix[b].name != par.rout && matrix[b].polarity == "positive" && !/gto|gbo/ig.test(matrix[b].name)){
			a.push(b)
		}
		return a;
	},[])

	if(GEN.isLayerExists({job:job, layer:par.rout}) == false){ // 检查外形层别是否存在
		throw "外形层" + par.rout + "不存在!"
	}

	var steplist = GEN.getStepList({job:job})
	steplist = steplist.filter(function(v){
		var tmpreg = new RegExp(par.step_filter,"ig")
		return tmpreg.test(v)
	})
	if (steplist.length == 0 && par.step2) {
		steplist = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	steplist.forEach(function(step){
		GEN.openStep({job:job,name:step})
		var layerEmpty = GEN.isLayerEmpty({job:job, step:step, layer:par.rout}) 
		if(layerEmpty != false){ // 检查外形层是否为空
			throw "外形层" + par.rout + "为空!"
		}
		//料号初始化
		GEN.clearLayers();  //清除层显示
		GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响
		//操作模式初始化
		GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.units({ type: par.units });  //单位初始化
		GEN.zoomHome();  //窗口显示回到原始位置
		GEN.workLayer({name:par.rout, display_number:1, clear_before:'yes'});
		var cp_rout = "new_" + par.rout;
		//拷贝外形层到辅助层并涨大
		GEN.copyLayer({source_job:job, source_step:step, source_layer:par.rout, dest_layer:cp_rout});
		// GEN.selResize({size: par.ol_resize_value}); // 外形扩大 2um
		GEN.affectedLayer({affected:'yes', layer:board_layer, clear_before:'yes'});
		//参考选择
		GEN.selRefFeat({
			'layers': cp_rout,
			'use':'filter',
			'mode':'cover',
			'polarity':'positive',
			'f_types':'arc\;line',
			'filter':{
				'feat_types':'line\;pad\;surface\;arc\;text',
				'polarity':'positive\;negative',
				'include_syms':'',
				'exclude_syms':'',
			}
		});
		if(GEN.getSelectCount() > 0){
			GEN.selDelete()	// 将被外形包含的物件删除
		}

		GEN.deleteLayer({job:job, step:step, layer:cp_rout}) //删除复制的层
		GEN.affectedLayer({affected:'no',mode:'all'})
		var tmp_board_layers = board_layer.filter(function(v) {return  v!="ol"})
		if(tmp_board_layers.length){
			tmp_board_layers.forEach(function(layer){
				GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
				GEN.COM("filter_set,filter_name=popup,update_popup=no,feat_types=line")
				GEN.COM("filter_set,filter_name=popup,update_popup=no,polarity=positive")
				GEN.COM("sel_ref_feat,layers="+par.rout+",use=filter,mode=touch,pads_as=shape,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,include_syms=,exclude_syms=")
				GEN.COM("filter_reset,filter_name=popup")
				// GEN.COM("filter_reset,filter_name=popup")
				if(GEN.getSelectCount()>0){ 
					GEN.PAUSE("please delete items")
					if(GEN.getSelectCount() > 0) {
						GEN.selDelete()
					}
				}
			})
		}
		GEN.clearLayers();
		GEN.affectedLayer({ mode: 'all', affected: 'no' });
	})

	//保存 
	if(/yes/ig.test(par.auto_save.toLowerCase())){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}